package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/blog/model"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// PostRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customPostRepository.
	PostRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.BlogPost, error) // ##24.11.30##
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.BlogPost, error) // ##24.11.30##
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.BlogPost, error) // ##24.11.30##
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogPost, int64, error) // ##24.11.30##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.BlogPost,
			rel *model.BlogPostRel,
		) error // ##24.11.30##
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.BlogPost,
			rel *model.BlogPostRel,
		) error
		UpdateBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64, cols model.M) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error // ##24.11.30##
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDeleteBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64) error

		GetDetailList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogPostDetail, int64, error) // ##24.11.30##
		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogAttachmentRelationship, int64, error) // ##24.11.30##
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogPostMetum, int64, error) // ##24.11.30##
		UpdateMeta(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.BlogPostMetum,
		) (err error)
	}

	customPostRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewPostRepository returns a repository for the database table.
func NewPostRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) PostRepository {
	return &customPostRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:cms:posts:id:",
		cacheIdExpirePrefix: "cache:cms:posts:id:expire:",
	}
}

func (r *customPostRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.BlogPost, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.BlogPost
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindBlogPost(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.BlogPost) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customPostRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.BlogPost, error) {
	cacheIdKey := r.formatPrimaryWithExpire(id)
	var resp model.BlogPost
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindBlogPost(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.BlogPost) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customPostRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.BlogPost, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindBlogPost(ctx, db, id)
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customPostRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogPost, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var statistic bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogPostColumns.ID+" DESC"))
					mods = append(mods, model.BlogPostWhere.ID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogPostColumns.ID+" ASC"))
					mods = append(mods, model.BlogPostWhere.ID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "search":
			if val, ok := v.(string); ok && len(val) > 0 { // 搜索
				likeVal := fmt.Sprintf("%%%s%%", val)
				mods = append(mods, qm.Where(fmt.Sprintf(
					"(%s LIKE ? OR %s LIKE ?)",
					model.BlogPostColumns.PostTitle,
					model.BlogPostColumns.PostName), likeVal, likeVal))
			}
		case "statistic":
			if val, ok := v.(string); ok && val == "1" { // 按 PostStatus 统计
				statistic = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogPostColumns.ID:
			mods = append(mods, modelx.GetIntMods(model.BlogPostColumns.ID, opMap)...)
		case model.BlogPostColumns.PostAuthorID:
			mods = append(mods, modelx.GetIntMods(model.BlogPostColumns.PostAuthorID, opMap)...)
		case model.BlogPostColumns.PostParentID:
			mods = append(mods, modelx.GetIntMods(model.BlogPostColumns.PostParentID, opMap)...)
		case model.BlogPostColumns.PostTitle:
			mods = append(mods, modelx.GetStringMods(model.BlogPostColumns.PostTitle, opMap)...)
		case model.BlogPostColumns.PostExcerpt:
			mods = append(mods, modelx.GetStringMods(model.BlogPostColumns.PostExcerpt, opMap)...)
		case model.BlogPostColumns.PostStatus:
			if !statistic {
				mods = append(mods, modelx.GetIntMods(model.BlogPostColumns.PostStatus, opMap)...)
			}
		case model.BlogPostColumns.CommentStatus:
			mods = append(mods, modelx.GetIntMods(model.BlogPostColumns.CommentStatus, opMap)...)
		case model.BlogPostColumns.PostName:
			mods = append(mods, modelx.GetStringMods(model.BlogPostColumns.PostName, opMap)...)
		case model.BlogPostColumns.GUID:
			mods = append(mods, modelx.GetStringMods(model.BlogPostColumns.GUID, opMap)...)
		case model.BlogPostColumns.PostDate:
			mods = append(mods, modelx.GetTimeMods(model.BlogPostColumns.PostDate, opMap)...)
		case model.BlogPostColumns.PostModifiedDate:
			mods = append(mods, modelx.GetTimeMods(model.BlogPostColumns.PostModifiedDate, opMap)...)
		case model.BlogPostColumns.MenuOrder:
			mods = append(mods, modelx.GetIntMods(model.BlogPostColumns.MenuOrder, opMap)...)
		case model.BlogPostColumns.CommentCount:
			mods = append(mods, modelx.GetIntMods(model.BlogPostColumns.CommentCount, opMap)...)
		case model.BlogPostColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.BlogPostColumns.DeletedAt, opMap)...)
		}
	}

	if statistic {
		mods = append(mods, qm.Select(fmt.Sprintf(
			"%s, count(%s) as %s",
			model.BlogPostColumns.PostStatus,
			model.BlogPostColumns.PostStatus,
			model.BlogPostColumns.MenuOrder,
		)))
		mods = append(mods, qm.GroupBy(model.BlogPostColumns.PostStatus))
		preList, preErr := model.BlogPosts(mods...).All(ctx, r.mysqlConn)
		if preErr != nil {
			err = preErr
			return
		}

		return preList, 0, nil
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogPosts(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogPostColumns.ID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogPosts(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.BlogPost,
	rel *model.BlogPostRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		if rel == nil {
			return nil
		}

		postId := data.ID

		if rel.Detail != nil {
			rel.Detail.PostID = postId
			err = rel.Detail.Insert(ctx, db, boil.Infer())
			if err != nil {
				return err
			}
		}

		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				v.PostID = postId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				v.ObjectID = postId
				v.ObjectType = uint16(globalkey.AttachmentLogTypePost)
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.CategoryIds) > 0 {
			for _, tid := range rel.CategoryIds {
				var relationShip model.BlogTermRelationship
				relationShip.ObjectID = postId
				relationShip.ObjectType = uint16(globalkey.PostTypePost)
				relationShip.TermID = tid
				err = relationShip.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.TagIds) > 0 {
			for _, tid := range rel.TagIds {
				var relationShip model.BlogTermRelationship
				relationShip.ObjectID = postId
				relationShip.ObjectType = uint16(globalkey.PostTypePost)
				relationShip.TermID = tid
				err = relationShip.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Term) > 0 {
			for _, v := range rel.Term {
				v.ObjectID = postId
				v.ObjectType = uint16(globalkey.PostTypePost)
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.BlogPost,
	rel *model.BlogPostRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		if data != nil {
			blacklist := []string{
				model.BlogPostColumns.ID,
				model.BlogPostColumns.DeletedAt,
			}
			if rel != nil && len(rel.Blacklist) > 0 {
				blacklist = append(blacklist, rel.Blacklist...)
			}
			rowsAff, err := data.Update(ctx, db, boil.Blacklist(blacklist...))
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}
		}

		if rel == nil {
			return nil
		}

		postId := data.ID
		if rel.Detail != nil {
			_, err := rel.Detail.Update(ctx, db, boil.Blacklist(
				model.BlogPostDetailColumns.DetailID,
				model.BlogPostDetailColumns.PostID,
				model.BlogPostDetailColumns.PingStatus,
				model.BlogPostDetailColumns.ToPing,
				model.BlogPostDetailColumns.Pinged,
			))
			if err != nil {
				return err
			}
		}

		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				if v.MetaID > 0 {
					_, err := v.Update(ctx, db, boil.Blacklist(
						model.BlogPostMetumColumns.MetaID,
						model.BlogPostMetumColumns.PostID,
						model.BlogPostMetumColumns.MetaKey,
					))
					if err != nil {
						return err
					}
				} else {
					v.PostID = postId
					err := v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				if v.AttachmentRelationshipID > 0 {
					_, err := v.Update(ctx, db, boil.Blacklist(
						model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID,
						model.BlogAttachmentRelationshipColumns.ObjectID,
						model.BlogAttachmentRelationshipColumns.ObjectType,
						model.BlogAttachmentRelationshipColumns.AttachmentID,
					))
					if err != nil {
						return err
					}
				} else {
					v.ObjectID = postId
					v.ObjectType = uint16(globalkey.AttachmentLogTypePost)
					err := v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.CategoryIds) > 0 {
			for _, tid := range rel.CategoryIds {
				var relationShip model.BlogTermRelationship
				relationShip.ObjectID = postId
				relationShip.ObjectType = uint16(globalkey.PostTypePost)
				relationShip.TermID = tid
				err := relationShip.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.TagIds) > 0 {
			for _, tid := range rel.TagIds {
				var relationShip model.BlogTermRelationship
				relationShip.ObjectID = postId
				relationShip.ObjectType = uint16(globalkey.PostTypePost)
				relationShip.TermID = tid
				err := relationShip.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Term) > 0 {
			for _, v := range rel.Term {
				if v.TermRelationshipID > 0 {
					_, err := v.Update(ctx, db, boil.Blacklist(
						model.BlogTermRelationshipColumns.TermRelationshipID,
						model.BlogTermRelationshipColumns.ObjectID,
						model.BlogTermRelationshipColumns.ObjectType,
						model.BlogTermRelationshipColumns.TermID,
					))
					if err != nil {
						return err
					}
				} else {
					v.ObjectID = postId
					v.ObjectType = uint16(globalkey.PostTypePost)
					err := v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.DelMetaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.BlogPostMetumWhere.MetaID.IN(rel.DelMetaIds))
			_, err := model.BlogPostMeta(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		if len(rel.DelMediaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.BlogAttachmentRelationshipWhere.AttachmentRelationshipID.IN(rel.DelMediaIds))
			_, err := model.BlogAttachmentRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		if len(rel.DelTermIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.BlogTermRelationshipWhere.TermRelationshipID.IN(rel.DelTermIds))
			_, err := model.BlogTermRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.BlogPostWhere.ID.IN(ids))
			rowsAff, err := model.BlogPosts(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customPostRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.PostStatus == uint16(globalkey.PostStatusTrash) {
		return nil
	}

	data.DelStatus = data.PostStatus
	data.PostStatus = uint16(globalkey.PostStatusTrash)
	data.DeletedAt = null.TimeFrom(time.Now())
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.BlogPostColumns.DelStatus,
			model.BlogPostColumns.PostStatus,
			model.BlogPostColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.PostStatus != uint16(globalkey.PostStatusTrash) {
		return nil
	}

	data.PostStatus = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.BlogPostColumns.PostStatus,
			model.BlogPostColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) ForceDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Delete(ctx, db)
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotDeleted
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customPostRepository) ForceDeleteBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.BlogPostWhere.ID.IN(ids))

			rowsAff, err := model.BlogPosts(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotDeleted
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customPostRepository) getCacheKeys(data *model.BlogPost) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.ID)
	cacheIdExpireKey := r.formatPrimaryWithExpire(data.ID)
	cacheKeys := []string{
		cacheIdKey,
		cacheIdExpireKey,
	}

	return cacheKeys
}

func (r *customPostRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customPostRepository) formatPrimaryWithExpire(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdExpirePrefix, primary)
}

func (r *customPostRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
		resp = append(resp, r.formatPrimaryWithExpire(primary))
	}

	return resp
}

func (r *customPostRepository) queryPrimary(ctx context.Context, conn *sql.DB, v any, primary any) error {
	var pid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			pid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindBlogPost(ctx, conn, pid)
	if err != nil {
		return err
	}

	*v.(*model.BlogPost) = *data

	return nil
}

func (r *customPostRepository) GetDetailList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogPostDetail, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogPostDetailColumns.DetailID+" DESC"))
					mods = append(mods, model.BlogPostDetailWhere.DetailID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogPostDetailColumns.DetailID+" ASC"))
					mods = append(mods, model.BlogPostDetailWhere.DetailID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogPostDetailColumns.DetailID:
			mods = append(mods, modelx.GetIntMods(model.BlogPostDetailColumns.DetailID, opMap)...)
		case model.BlogPostDetailColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.BlogPostDetailColumns.PostID, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogPostDetails(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogPostDetailColumns.DetailID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogPostDetails(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogAttachmentRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID+" DESC"))
					mods = append(mods, model.BlogAttachmentRelationshipWhere.AttachmentRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID+" ASC"))
					mods = append(mods, model.BlogAttachmentRelationshipWhere.AttachmentRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.BlogAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.BlogAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentSource:
			mods = append(mods, modelx.GetStringMods(model.BlogAttachmentRelationshipColumns.AttachmentSource, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentImageURL:
			mods = append(mods, modelx.GetStringMods(model.BlogAttachmentRelationshipColumns.AttachmentImageURL, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentImageAlt:
			mods = append(mods, modelx.GetStringMods(model.BlogAttachmentRelationshipColumns.AttachmentImageAlt, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogPostMetum, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogPostMetumColumns.MetaID+" DESC"))
					mods = append(mods, model.BlogPostMetumWhere.MetaID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogPostMetumColumns.MetaID+" ASC"))
					mods = append(mods, model.BlogPostMetumWhere.MetaID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogPostMetumColumns.MetaID:
			mods = append(mods, modelx.GetIntMods(model.BlogPostMetumColumns.MetaID, opMap)...)
		case model.BlogPostMetumColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.BlogPostMetumColumns.PostID, opMap)...)
		case model.BlogPostMetumColumns.MetaKey:
			mods = append(mods, modelx.GetStringMods(model.BlogPostMetumColumns.MetaKey, opMap)...)
		case model.BlogPostMetumColumns.MetaValue:
			mods = append(mods, modelx.GetIntMods(model.BlogPostMetumColumns.MetaValue, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogPostMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogPostMetumColumns.MetaID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogPostMeta(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customPostRepository) UpdateMeta(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.BlogPostMetum,
) (err error) {
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.BlogPostMetumColumns.PostID,
			model.BlogPostMetumColumns.MetaKey,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}
		return nil
	}, r.getCacheKeys(&model.BlogPost{ID: data.PostID})...)

	return nil
}
